<script setup lang="ts">
import type { Recordable } from '@neucloud/types-base'
import { uniq } from 'lodash-es'

const props = defineProps<{
  isBatch?: boolean
  dates: string[]
  filledDates: Recordable<Recordable<number>>
}>()

const codeList = [
  { label: '代码1', value: 'code1' },
  { label: '代码2', value: 'code2' },
  { label: '代码3', value: 'code3' },
  { label: '代码4', value: 'code4' },
  { label: '代码5', value: 'code5' },
]
const codeMap = codeList.reduce(
  (map, item) => {
    map[item.value] = item
    return map
  },
  {} as Recordable<{ label: string; value: string }>,
)

const form = reactive({
  workCode: [],
  workTime: 0,
  mode: 'avg',
})

const columns = computed(() => {
  return [
    { label: '工时代码', property: 'code', minWidth: 140 },
    ...props.dates.map((date) => ({
      label: date.split('-').slice(1).join('-'),
      property: `$${date}`,
      minWidth: 120,
    })),
  ]
})

const data = ref<any[]>([])
function genData() {
  const { workTime, workCode, mode } = form
  const { filledDates, dates } = props
  const finalCodeList = uniq([...workCode, ...Object.keys(filledDates)])

  const _data = [] as any[]
  finalCodeList.forEach((item, index) => {
    const obj = { code: codeMap[item].label } as Recordable

    dates.forEach((date) => {
      const fillableWorkTime = 8 - (filledDates[item]?.[date] || 0)
      const rest = 8 % workCode.length

      let value = filledDates[item]?.[date] || fillableWorkTime
      if (mode === 'avg') {
        value = Math.floor(value / finalCodeList.length)
        if (index === 0 && rest > 0) value += rest
      }
      else if (mode === 'fill') {
        value = workTime
      }

      obj[`$${date}`] = value
    })
    _data.push(obj)
  })

  data.value = _data
}

watch(() => form, genData, { deep: true })

const activeCell = ref('')

function handleCellClick(row, column, cell) {
  activeCell.value = `${data.value.findIndex((item) => item.code === row.code)}${column.id}`
  nextTick(() => {
    const inputEle = cell.querySelector('input') as HTMLInputElement
    if (inputEle) {
      inputEle.focus()
      inputEle.select()

      const callback = () => {
        activeCell.value = ''
        inputEle?.removeEventListener('blur', callback)
      }
      inputEle.addEventListener('blur', callback)
    }
  })
}
</script>

<template>
  <ElForm
    :inline="true"
    :model="form"
    label-suffix="："
  >
    <ElFormItem
      label="姓名"
      prop="workTime"
    >
      <span class="readonly-text">张三</span>
    </ElFormItem>
    <ElFormItem
      label="部门"
      prop="department"
    >
      <span class="readonly-text">行业应用部</span>
    </ElFormItem>
    <ElFormItem
      label="填报月份"
      prop="month"
    >
      <span class="readonly-text">2023-08</span>
    </ElFormItem>

    <br>

    <ElFormItem
      label="工时代码"
      prop="workTime"
    >
      <ElSelect
        v-model="form.workCode"
        placeholder="请选择工时代码"
        :filterable="true"
        :multiple="true"
        :multiple-limit="2"
      >
        <ElOption
          v-for="item in codeList"
          :key="item.value"
          :value="item.value"
          :label="item.label"
        />
      </ElSelect>

      <ElTag
        v-for="item in ['code1', 'code2']"
        :key="item"
        :closable="false"
        style="margin-left: 10px"
      >
        {{ codeMap[item].label }}
      </ElTag>
    </ElFormItem>

    <br>

    <ElFormItem
      label="填写工时"
      prop="workTime"
    >
      <ElInputNumber
        v-model="form.workTime"
        :min="0"
        :max="8"
        :precision="0"
        :value-on-clear="0"
      />
    </ElFormItem>

    <ElFormItem
      label="填充模式"
      prop="mode"
    >
      <ElRadioGroup v-model="form.mode">
        <ElRadio label="avg">
          智能均分
        </ElRadio>
        <ElRadio label="fill">
          固定填充
        </ElRadio>
      </ElRadioGroup>
    </ElFormItem>
  </ElForm>

  <ElDivider />

  <ElTable
    :border="true"
    :stripe="true"
    :data="data"
    @cell-click="handleCellClick"
  >
    <ElTableColumn
      v-for="item in columns"
      :key="item.property"
      v-bind="item"
      align="center"
    >
      <template #default="{ row, column, $index }">
        <!-- TODO: max 应该为当天剩余工时数 -->
        <ElInputNumber
          v-if="column.property !== 'code' && activeCell === `${$index}${column.id}`"
          v-model="row[column.property]"
          size="small"
          :min="0"
          :max="8"
          :precision="0"
          :controls="false"
          style="width: 100px"
        />
        <span
          v-else
          style="display: inline-flex; align-items: center; height: 30px"
        >{{ row[column.property] }}</span>
      </template>
    </ElTableColumn>
  </ElTable>
</template>

<style lang="scss" scoped>
.readonly-text {
  display: inline-flex;
  width: 200px;
}
</style>
